import { queryMaterialDetail } from '@/api/basicManagement/materielList'

export default {
  beforeRouteLeave(to, form, next) {
    if (form.name) {
      this.upDownVis = false
    }
    next()
  },
  methods: {
    // 监听库位 库位切换
    handelCode(index) {
      const item = this.tableData[index]
      item.codes.forEach(res => {
        if (item.fcodefnumber === res.fnumber) {
          item.fcodeQty = res.fqty
        }
      })
    },
    // 监听库位 库位切换
    handelCode1(index) {
      const item = this.tableData[index]
      item.codes.forEach(res => {
        if (item.finpositionid === res.fpositionid) {
          item.fcodeQty = res.fqty
        }
      })
    },
    // 监听库位 库位切换
    handelCode2(index) {
      const item = this.tableData[index]
      item.codes.forEach(res => {
        if (item.fcodeid === res.fid) {
          item.fcodeQty = res.fqty
        }
      })
    },
    // 跳转物料主数据
    jumpMateriel() {
      if (!this.prodValue.FNUMBER.trim()) {
        this.$message.error('物料编码为空,不能跳转！')
        return
      }
      queryMaterialDetail({ fnumber: this.prodValue.FNUMBER }).then(res => {
        if (res.code === 0) {
          this.$router.push({ path: `/detailMateriel/${this.prodValue.FNUMBER}` })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message.error(error)
      })
    },
    // 子物料编码跳转bom数据
    sonJumpMateriel(FNUMBER) {
      if (!FNUMBER) {
        this.$message.error('物料编码为空,不能跳转！')
        return
      }
      this.$router.push({ path: `/detailMateriel/${FNUMBER}` })
    },
    // 自定义合计行
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return (Number(prev) + Number(curr)).toFixed(2)
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      sums.forEach((res, index) => {
        if (Number(sums[index]) > 0) {
          sums[index] = Number(sums[index]).toLocaleString()
        } else {
          sums[index] = ''
        }
      })
      sums[0] = '合计'
      return sums
    }
  }
}
